package com.gitee.qdbp.general.thirdpart.biz;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.gitee.qdbp.general.thirdpart.enums.TradeState;
import com.gitee.qdbp.tools.utils.DateTools;
import com.gitee.qdbp.tools.utils.VerifyTools;

public abstract class PayUtils {

    public static TradeState parseTradeState(String string) {
        if (VerifyTools.isBlank(string)) {
            return null;
        } else {
            try {
                return TradeState.valueOf(string);
            } catch (Exception e) {
                return null;
            }
        }
    }

    public static Date parseDate(String string) {
        if (VerifyTools.isBlank(string)) {
            return null;
        } else {
            try {
                return DateTools.parse(string);
            } catch (Exception e) {
                return null;
            }
        }
    }

    public static Double parseDouble(String string) {
        if (VerifyTools.isBlank(string)) {
            return null;
        } else {
            try {
                return Double.valueOf(string);
            } catch (Exception e) {
                return null;
            }
        }
    }

    public static String mapToParams(Map<String, ?> params) {
        StringBuilder buffer = new StringBuilder();
        List<String> keys = new ArrayList<>(params.keySet());
        Collections.sort(keys);
        for (String key : keys) {
            Object value = params.get(key);
            if (VerifyTools.isNoneBlank(key, value)) {
                buffer.append(buffer.length() == 0 ? "" : "&").append(key).append("=").append(value);
            }
        }
        return buffer.toString();
    }

    public static Map<String, String> paramsToMap(String string) {
        Map<String, String> params = new HashMap<>();
        String[] entries = string.split("&");
        for (String entry : entries) {
            if (entry.indexOf('=') >= 0) {
                String[] words = entry.split("=");
                params.put(words[0], words[1]);
            }
        }
        return params;
    }

    public static Map<String, Object> toKeyObjectMap(Map<String, ?> src) {
        Map<String, Object> map = new HashMap<>();
        for (Entry<String, ?> entry : src.entrySet()) {
            map.put(entry.getKey(), entry.getValue());
        }
        return map;
    }

    public static boolean inArray(Object value, Object[] array) {
        if (VerifyTools.isBlank(array)) {
            return false;
        }
        for (Object s : array) {
            if (VerifyTools.equals(s, value)) {
                return true;
            }
        }
        return false;
    }
}
